package com.igo.onepack.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;

public class CMDUtils {

    private static final String TAG = "CMDUtils";

    private CMDUtils() {}

    public static void exec(Callback callback, String... command) {
        try {
            ProcessBuilder builder = new ProcessBuilder(command);
            // 重定向错误流到标准输出流
            builder.redirectErrorStream(true);
            // stdout
            Process process = builder.start();
            // start the process and start a new thread to handle the stream
            // input
            ProcessHandleRunnable processHandleRunnable = new ProcessHandleRunnable(process,callback);
            new Thread(processHandleRunnable).start();
            processHandleRunnable.countDownLatch.await();
//            process.waitFor(); // wait if needed
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            Log.e(TAG,"cmd exec error.",e);
        }
    }

    static class ProcessHandleRunnable implements Runnable {
        private Process process;
        private Callback callback;
        private CountDownLatch countDownLatch;

        ProcessHandleRunnable(Process process, Callback callback) {
            this.process = process;
            this.callback = callback;
            this.countDownLatch = new CountDownLatch(1);
        }

        public void run() {
            BufferedReader br = null;
            InputStreamReader reader = null;
            try {
                callback.onStartExec();
                reader = new InputStreamReader(process.getInputStream());
                br = new BufferedReader(reader);
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
                countDownLatch.countDown();
                callback.onStopExec();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (br != null)
                        br.close();
                    if (reader != null)
                        reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public interface Callback {
        default void onStartExec() {}
        default void onStopExec() {}
    }
}